var DBFactory = require('../db/mysql_db');
var bannerDao = module.exports;

bannerDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'replace into shop_banner set ? ';
    DBFactory.poolQuery(sql, data,
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('save Err: ' + err);
                return;
            }
            cb(null, '添加或编辑成功！');
        }
    );
}

bannerDao.delete = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = ' delete from shop_banner where id = ? ';
    DBFactory.poolQuery(sql, [data.id],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('delete Err: ' + err);
                return;
            }
            cb(null, '删除成功！');
        }
    );
}

bannerDao.show = function(data, cb) {
    var sql = 'select * from  shop_banner order by id desc limit 3 ';
    DBFactory.poolQuery(sql, [],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('show Err: ' + err);
                return;
            }
            cb(null, result);
        }
    );
}

bannerDao.list = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql_total = 'select count(*) as count from shop_banner ';
    DBFactory.poolQuery(sql_total, [],
        function(){
            cb('no collection');
        },function (err,total) {
            if(err){
                cb(err);
                console.log('total Err: ' + err);
                return;
            }
            var sql = 'select * from shop_banner limit ?, ?';
            DBFactory.poolQuery(sql, [],
                function(){
                    cb('no collection');
                },function (err,result) {
                    if(err){
                        cb(err);
                        console.log('list Err: ' + err);
                        return;
                    }
                    var bannerList = {};
                    bannerList.total = total[0].count;
                    bannerList.msg = '';
                    bannerList.code = 200;
                    bannerList.data = result;
                    cb(null, bannerList);
                }
            );
        }
    );
}